package com.itic.market.system.productjd.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.itic.appbase.applications.sys.syssetting.persistence.dao.SysSettingDao;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.market.mobile.jd.MallJdUtils;
import com.itic.market.system.marketuserproduct.persistence.dao.MarketUserProductDao;
import com.itic.market.system.marketuserproduct.persistence.model.MarketUserProduct;
import com.itic.market.system.productjd.persistence.dao.ProductJdDao;
import com.itic.market.system.productjd.persistence.model.ProductJd;
import com.itic.market.system.productjd.persistence.model.ProductJdExample;
import com.itic.market.system.profitmoney.persistence.dao.ProfitMoneyDao;
import com.itic.market.system.profitmoney.persistence.model.ProfitMoney;
import com.itic.market.system.user.persistence.dao.MarketUserDao;
import com.itic.market.system.user.persistence.model.MarketUser;


@Service
@Transactional
public class ProductJdService
     extends CrudService<ProductJdDao,ProductJd,ProductJdExample> {
    @Autowired
    private SysSettingDao sysSettingDao;
    @Autowired
    private MarketUserDao marketUserDao;
    @Autowired
    private MarketUserProductDao marketUserProductDao;
    @Autowired
    private ProfitMoneyDao profitMoneyDao;

    public void testJdMoney(List<MarketUser> list) {
		for( MarketUser tmp : list ){
			String money="10";
			//平分为二与店主
    		money = NumberStringHelper.divString(money, "2", 2);
    		
			ProfitMoney profit = getProfitMoney( tmp, money ,"店主“"+tmp.getUserNickName()+"”分享京东商品赚取佣金"+money+"元","003");
			profitMoneyDao.insert(profit);
			
			//添加云店上店用户佣金
			marketUserDao.updateByPrimaryKey(resetMarketUserProfit(tmp,money));
			
			//添加三级分销的功能提成
			String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
			String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
	        String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
			String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
			//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
			MarketUser invitingUser = marketUserDao.selectByPrimaryKey(tmp.getInvitingId());
			if( null != invitingUser ){
				String successPeople = "0";
				if( StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
					successPeople = invitingUser.getSuccessPeople();
				}
				if( null != invitingUser && NumberStringHelper.isGreater(successPeople, one ) ){
					String moneyOne = getPercentMoney(money, onePercent );
					//添加收益记录
					ProfitMoney profitOne = getProfitMoney( invitingUser,moneyOne,"上级云店主“"+invitingUser.getUserNickName()+"”成功获取京东商品佣金提成"+moneyOne+"元","004");
					profitMoneyDao.insert(profitOne);
					//添加云店用户
					marketUserDao.updateByPrimaryKey(resetMarketUserProfit(invitingUser,moneyOne));
    			    
    			    //查找商家的上上级信息
    				MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
    				if( null != topInvitingUser ){
    					String successPeopleTwo = "0";
	    				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
	    					successPeopleTwo = topInvitingUser.getSuccessPeople();
	    				}
	    				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
	    					String moneyTwo = getPercentMoney(money, twoPercent );
	    					//添加收益记录
	    					ProfitMoney profitTwo = getProfitMoney( topInvitingUser,moneyTwo,"上上级云店主“"+topInvitingUser.getUserNickName()+"”成功获取京东商品佣金提成"+moneyTwo+"元","004");
	    					profitMoneyDao.insert(profitTwo);
	    					//添加云店用户
	    					marketUserDao.updateByPrimaryKey(resetMarketUserProfit(topInvitingUser,moneyTwo));
	    				}
    				}
    				
				}
			}
		}
	}
	
    
	public void syncJdMoney(List<MarketUser> list) {
		for( MarketUser tmp : list ){
			
			Date date = new Date();
	    	Date dateBefore = CalendarHelper.getDateBefore(date, 1);
	    	long startTime = dateBefore.getTime();
	    	long endTime = date.getTime();
			
		    JSONObject object = MallJdUtils.queryCommissionByUserId(tmp.getId(), startTime, endTime);
		    String code = object.getString("code");
		    if( "0".equals(code) ){
		    	JSONObject jsonObject = object.getJSONObject("result");
		    	String money = jsonObject.getString("actincome");
		    	//money = "100";
		    	boolean greater = NumberStringHelper.isGreaterNoEqual(money, "0");
		    	if(greater){
		    		//平分为二与店主
		    		money = NumberStringHelper.divString(money, "2", 2);
		    		
					ProfitMoney profit = getProfitMoney( tmp, money ,"店主“"+tmp.getUserNickName()+"”分享京东商品赚取佣金"+money+"元","001");
					profitMoneyDao.insert(profit);
					
					//添加云店上店用户佣金
					marketUserDao.updateByPrimaryKey(resetMarketUserProfit(tmp,money));
					
					//添加三级分销的功能提成
    				String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
    				String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
    		        String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
    				String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
    				//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
    				MarketUser invitingUser = marketUserDao.selectByPrimaryKey(tmp.getInvitingId());
    				if( null != invitingUser ){
    					String successPeople = "0";
        				if( StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
        					successPeople = invitingUser.getSuccessPeople();
        				}
        				if( null != invitingUser && NumberStringHelper.isGreater(successPeople, one ) ){
        					String moneyOne = getPercentMoney(money, onePercent );
        					//添加收益记录
        					ProfitMoney profitOne = getProfitMoney( invitingUser,moneyOne,"上级云店主“"+invitingUser.getUserNickName()+"”成功获取京东商品佣金提成"+moneyOne+"元","002");
        					profitMoneyDao.insert(profitOne);
        					//添加云店用户
        					marketUserDao.updateByPrimaryKey(resetMarketUserProfit(invitingUser,moneyOne));
    	    			    
    	    			    //查找商家的上上级信息
    	    				MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
    	    				if( null != topInvitingUser ){
    	    					String successPeopleTwo = "0";
    		    				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
    		    					successPeopleTwo = topInvitingUser.getSuccessPeople();
    		    				}
    		    				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
    		    					String moneyTwo = getPercentMoney(money, twoPercent );
    		    					//添加收益记录
    		    					ProfitMoney profitTwo = getProfitMoney( topInvitingUser,moneyTwo,"上上级云店主“"+topInvitingUser.getUserNickName()+"”成功获取京东商品佣金提成"+moneyTwo+"元","002");
    		    					profitMoneyDao.insert(profitTwo);
    		    					//添加云店用户
    		    					marketUserDao.updateByPrimaryKey(resetMarketUserProfit(topInvitingUser,moneyTwo));
    		    				}
    	    				}
    	    				
        				}
    				}
    				
		    	}
		    }
		}
	}
	
	
	 /**
     * 返回一个百分比的金额
     * @param money
     * @param percent
     * @return
     */
    public String getPercentMoney( String money, String percent ){
    	String replace = percent.replace("%", "");
    	String mulString = NumberStringHelper.mulString(money, replace);
    	String divString = NumberStringHelper.divString(mulString, "100", 0);
    	return divString;
    }
	
	 /**
     * 
     * @param order 订单
     * @param user VIP购买用户
     * @param money 云店用户
     * @param note 备注信息
     * @param type 类型
     * @return
     */
    public ProfitMoney getProfitMoney( MarketUser user, String money, String note ,String type ){
    	
    	ProfitMoney profitMoney = new ProfitMoney();
    	profitMoney.setId(IdGen.uuid());
    	profitMoney.setIsEffective(DBConst.TRUE);
    	profitMoney.setCreateTime(new Date());
    	profitMoney.setUpdateTime(new Date());
    	profitMoney.setCreateUser("unknown");
    	profitMoney.setOrgCode("unknown");
    	
    	profitMoney.setUserId(user.getId());
    	profitMoney.setMarketUserId(user.getId());
        profitMoney.setType(type);
        profitMoney.setNote(note);
        profitMoney.setMoney(money);
        profitMoney.setUserNickName(user.getUserNickName());
    	
    	profitMoney.setOrderId(user.getId());
    	profitMoney.setOrderNum("京东收益");
    	profitMoney.setOrderPayTime(new Date());
    	profitMoney.setOrderTotalMoney(money);
		
    	return profitMoney;
    }
    
    /**
     * 添加云店商品共赚了多少钱
     * @param marketUserProductId
     * @param money
     * @return
     */
    public MarketUserProduct resetMarketUserProductProfit( String marketUserProductId, String money ){
    	//设置云店主的商品共赚了多少钱
	    MarketUserProduct marketUserProduct = marketUserProductDao.selectByPrimaryKey(marketUserProductId);
		String marketUserProductMoney = "0";
		if( StringHelper.isNotBlank(marketUserProduct.getProfit()) ){
			marketUserProductMoney = marketUserProduct.getProfit();
		}
		marketUserProductMoney = NumberStringHelper.addString(marketUserProductMoney, money );
		marketUserProduct.setProfit(marketUserProductMoney);
		return marketUserProduct;
    }
    
    /**
     * 添加云店收益
     * @param user
     * @return
     */
    public MarketUser resetMarketUserProfit( MarketUser user, String money ){
		//添加商家账户收益
		String marketUserMoney = "0";
		if( StringHelper.isNotBlank(user.getMoney()) ){
			marketUserMoney = user.getMoney();
		}
		marketUserMoney = NumberStringHelper.addString(marketUserMoney, money);
		user.setMoney(marketUserMoney);
		
		/*//预计收益相减
		String marketUserPreMoney = "0";
		if( StringHelper.isNotBlank(user.getPreProfit()) ){
			marketUserPreMoney = user.getPreProfit();
		}
		marketUserPreMoney = NumberStringHelper.subtractString( marketUserPreMoney, money );
		user.setPreProfit(marketUserPreMoney);*/
		
		//统计总收益信息
		String marketUserTotalMoney = "0";
		if( StringHelper.isNotBlank(user.getTotalProfit()) ){
			marketUserTotalMoney = user.getTotalProfit();
		}
		marketUserTotalMoney = NumberStringHelper.addString( marketUserTotalMoney, money );
		user.setTotalProfit(marketUserTotalMoney);
		
		return user;
    }


    /**
	 * 获得京东二合一接口
	 * @param skuNum
	 * @param position
	 * @return
	 */
	public String getCommonLinkByDdt( String skuNum, String position ){
		String result = "";
		String initUrl = "http://develop.jhjvip.cn:8081/ddt/mobile/jdlm/getUrl?sku=";
		String byKey = sysSettingDao.getByKey("DDT_WWW_ADDRESS");
		if( StringHelper.isNotBlank(byKey) ){
			initUrl = byKey;
		}
		initUrl = initUrl + skuNum;
		
		if( StringHelper.isNotBlank(position) ){
			initUrl = initUrl+"&pid="+position;
		}
		String httpGet = HttpRequestUtils.httpGet(initUrl);
		net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(httpGet);
		String resultHttp = fromObject.getString("code");
		if( "10000".equals(resultHttp) ){
			result = fromObject.getString("data");
		}
		return result;
	}
	
	/**
	 * 获得京东优惠券接口
	 * @param skuNum
	 * @param conUrl
	 * @param position
	 * @return
	 */
	public String getConLinkByDdt( String skuNum, String conUrl, String position ){
		String result = null;
		String initUrl = "http://develop.jhjvip.cn:8081/ddt/mobile/jdlm/getConUrl";
		String byKey = sysSettingDao.getByKey("DDT_WWW_ADDRESS");
		if( StringHelper.isNotBlank(byKey) ){
			initUrl = byKey;
		}
		try {
			conUrl = URLEncoder.encode(conUrl,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String tempParam = "sku=" + skuNum +"&conUrl="+conUrl;
		
		if( StringHelper.isNotBlank(position) ){
			tempParam += "&pid="+position;
		}
		String httpGet = HttpRequestUtils.sendPost(initUrl, tempParam);
		
		net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(httpGet);
		String resultHttp = fromObject.getString("code");
		if( "10000".equals(resultHttp) ){
			result = fromObject.getString("data");
		}
		return result;
	}
}